package br.pucrs.lognplay.service;

import java.util.List;

import javax.ejb.Stateless;

import br.pucrs.lognplay.entity.Tag;
import br.pucrs.lognplay.repository.RepositoryManager;
import br.pucrs.lognplay.repository.TagRepository;

@Stateless
public class TagManagementServiceBean implements TagManagementService {

	public void mergeTag(Tag tag) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			TagRepository tagRepository = RepositoryManager.getTagRepository();
			tagRepository.merge(tag);
			RepositoryManager.commitTransaction();
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on merge a tag", e);
		}
	}

	public Tag getTagById(String id) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			TagRepository tagRepository = RepositoryManager.getTagRepository();
			Tag tag = tagRepository.get(id);
			RepositoryManager.commitTransaction();
			return tag;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on get a tag by id", e);
		}
	}

	public List<Tag> listAllTags() throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			TagRepository tagRepository = RepositoryManager.getTagRepository();
			List<Tag> tags = tagRepository.listAll();
			RepositoryManager.commitTransaction();
			return tags;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on list all tags", e);
		}
	}

	public List<Tag> listTagsByClientId(String clientId) throws ServiceException {
		try {
			RepositoryManager.beginTransaction();
			TagRepository tagRepository = RepositoryManager.getTagRepository();
			List<Tag> tags = tagRepository.listByClientId(clientId);
			RepositoryManager.commitTransaction();
			return tags;
		} catch (Exception e) {
			RepositoryManager.rollbackTransaction();
			throw new ServiceException("Error on list tags by client id", e);
		}
	}
}
